﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using WebAPI.Models;

namespace WebAPI.Controllers
{
    public class AreaController : BaseApiController
    {
        public IEnumerable<Area> GetAreaByParentId(int id)
        {
            var list = from a in db.Area where a.ParentId == id select a;
            // 

            
            return list;
        }

        [HttpPost]
        public bool EditAddress()
        {
            bool result = false;
            string name = HttpContext.Current.Request.Form["name"];
            string tel = HttpContext.Current.Request.Form["tel"];
            string area = HttpContext.Current.Request.Form["area"];
            string address = HttpContext.Current.Request.Form["address"];
            int userId = Convert.ToInt32(HttpContext.Current.Request.Form["userId"]);
            int isAdd = Convert.ToInt32(HttpContext.Current.Request.Form["isAdd"]);
            int addressId = Convert.ToInt32(HttpContext.Current.Request.Form["addressId"]);

            if (isAdd == 1)
            {
                //新建
                result = Insert(name, tel, area, address, userId);
            }
            else
            {
                //更新
                result=Update(name, tel, area, address, userId, addressId);
            }

            return result;
        }

        private bool Insert(string name, string tel, string area, string address, int userId)
        {
            bool result = false;
            ConsigneeAddress ca = new ConsigneeAddress() { UserId = userId, ConsigneeName = name, ConsigneeTel = tel, ConsigneeArea = area, AddressDetail = address };
            db.ConsigneeAddress.Add(ca);
            int n = db.SaveChanges();
            if (n > 0)
            {
                result = true;
            }
            return result;
        }

        private bool Update(string name, string tel, string area, string address, int userId,int addressId)
        {
            try
            {
                var ca = db.ConsigneeAddress.FirstOrDefault((p) => p.Id == addressId);
                if (ca != null)
                {
                    ca.ConsigneeName = name;
                    ca.ConsigneeTel = tel;
                    ca.ConsigneeArea = area;
                    ca.AddressDetail = address;
                    db.SaveChanges();
                    return true;
                }
                else
                    return false;
            }
            catch (Exception e)
            {
                return false;
            }
        }
    }
}
